package br.com.players.service;

import java.util.List;

import javax.persistence.Query;

import br.com.players.model.Convite;
import br.com.players.model.Player;
import br.com.players.model.Time;
import br.com.players.model.TimePlayer;

public class CadastroConviteService extends PlayersService {

	public String inserirConvite(String email, String idTime) {
		CadastroPlayerService cps = new CadastroPlayerService();
		
		Player player = cps.findPlayerByEmail(email);
		
		if(player == null) {
			return "-1";
		}
		
		Convite convite = new Convite();
		
		CadastroTimeService cts = new CadastroTimeService();
		
		Time time = cts.buscarTimePeloId(Long.parseLong(idTime));
		
		if(time == null) {
			return "0";
		}
		
		convite.setIdPlayer(player.getKey());
		convite.setIdTime(Long.parseLong(idTime));
		convite.setStatus("P");
		convite.setMensagem("Ola " + player.getNome() + " voce foi convidado para participar do time " + time.getNome() + "! Deseja aceitar?");
	
		super.persist(convite);
		
		return "1";
	}
	
	public List<Convite> buscarConvitesPorPlayer(String id) {
		final Query query = em.createQuery("select c from Convite c where c.status = 'P' and c.idPlayer = :idPlayer");
		query.setParameter("idPlayer", Long.parseLong(id));
		
		return query.getResultList();
	}
	
	public String removerConvitePorID(String id) {
		final Query query = em.createQuery("select c from Convite c where c.status = 'P' and c.id = :id");
		query.setParameter("id", Long.parseLong(id));
		
		Convite convite = (Convite) query.getSingleResult();
		
		if(convite == null) {
			return "0";
		}
		
		convite.setStatus("R");
		
		super.update(convite);
		
		return "1";
	}
	
	public String inserirPlayerTime(String idTime, String idPlayer, String idConvite) {
		final Query query = em.createQuery("select c from Convite c where c.status = 'P' and c.id = :idConvite");
		query.setParameter("idConvite", Long.parseLong(idConvite));
		
		Convite convite = (Convite) query.getSingleResult();
		
		if(convite == null) {
			return "0";
		}
		
		convite.setStatus("A");
		
		super.update(convite);
		
		TimePlayer tp = new TimePlayer();
		
		tp.setIdPlayer(Long.parseLong(idPlayer));
		tp.setIdTime(Long.parseLong(idTime));
		
		super.persist(tp);
		
		return "1";
	}
}
